import React, { useRef, useState, useCallback, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, StatusBar, ActivityIndicator } from 'react-native';
import PagerView from 'react-native-pager-view';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Svg, { Path } from 'react-native-svg';
import Video from 'react-native-video';

import PlayIcon from '@assets/svgs/play_icon.svg';
import FastImage from '@d11/react-native-fast-image';
import { FlashList } from '@shopify/flash-list';
import { pxToVh, pxToVw } from '@utils/pxToVx';

import { BusinessAPI } from '@/api/reworkAPI';
import { downloadFile } from '@/utils/downloadFile.ts';
import { videoCache } from '@/utils/mediaCache/videoCache';
import { ShareSingleton } from '@/utils/share';
import { showToast } from '@/utils/showToast';

// Download Icon SVG Component
const DownloadIcon = () => (
  <Svg width="16" height="16" viewBox="0 0 24 24" fill="none">
    <Path d="M12 16L7 11H10V4H14V11H17L12 16Z" fill="#555555" />
    <Path d="M5 20V18H19V20H5Z" fill="#555555" />
  </Svg>
);

// Share Icon SVG Component
const ShareIcon = () => (
  <Svg width="16" height="16" viewBox="0 0 24 24" fill="none">
    <Path
      d="M18 16.08C17.24 16.08 16.56 16.38 16.04 16.85L8.91 12.7C8.96 12.47 9 12.24 9 12C9 11.76 8.96 11.53 8.91 11.3L15.96 7.19C16.5 7.69 17.21 8 18 8C19.66 8 21 6.66 21 5C21 3.34 19.66 2 18 2C16.34 2 15 3.34 15 5C15 5.24 15.04 5.47 15.09 5.7L8.04 9.81C7.5 9.31 6.79 9 6 9C4.34 9 3 10.34 3 12C3 13.66 4.34 15 6 15C6.79 15 7.5 14.69 8.04 14.19L15.16 18.35C15.11 18.56 15.08 18.78 15.08 19C15.08 20.61 16.39 21.92 18 21.92C19.61 21.92 20.92 20.61 20.92 19C20.92 17.39 19.61 16.08 18 16.08Z"
      fill="#555555"
    />
  </Svg>
);

const VideoCard = ({ video }: { video: Face.History }) => {
  const handleDownload = () => {
    // Implement download functionality
    console.log('Download video:', video.id);
    const file = video.videoUrl;
    console.log('start======================');
    console.log('file = ', file);
    console.log('end========================');
    if (file && file.includes('mp4')) {
      const filename: string = file.split('/').pop() ?? '';
      downloadFile.downloadMediaFile(file, filename, 'video');
    }
  };

  const handleShare = async () => {
    // Implement share functionality
    console.log('Share video:', video.id);
    const url = await videoCache.getVideoUri(
      'https://obs-turingsyn-prod.obs.cn-east-3.myhuaweicloud.com/dreamona_web_resource/%E6%96%87%E7%94%9F%E8%A7%86%E9%A2%91/%E9%AB%98%E5%93%81%E8%B4%A8_16x9_A_whimsical_train_covered_in_sof.mp4',
    );
    ShareSingleton.getInstance().shareVideo(url);
  };

  return (
    <View style={styles.videoCard}>
      <View style={styles.videoPreview}>
        <Video source={{ uri: video.videoUrl }} resizeMode="cover" repeat muted={true} style={styles.video} />
        {/* <View style={styles.playButton}>
          <PlayIcon width={pxToVw(20)} height={pxToVw(20)} />
        </View> */}
      </View>
      <View style={styles.videoInfo}>
        {/* Left side - Title and metadata */}
        <View style={styles.videoInfoContent}>
          <Text style={styles.videoTitle}>{video.title}</Text>
          <Text style={styles.videoDuration}>• {video.duration}</Text>
          {/* <Text style={styles.videoCreated}>Created {video.created}</Text> */}
        </View>

        {/* Right side - Actions and status */}
        <View style={styles.rightContainer}>
          {/* Action Buttons */}
          <View style={styles.actionButtonsContainer}>
            <TouchableOpacity style={styles.actionButton} onPress={handleDownload} activeOpacity={0.7}>
              <View style={styles.actionButtonInner}>
                <DownloadIcon />
              </View>
            </TouchableOpacity>

            <TouchableOpacity style={styles.actionButton} onPress={handleShare} activeOpacity={0.7}>
              <View style={styles.actionButtonInner}>
                <ShareIcon />
              </View>
            </TouchableOpacity>
          </View>

          {/* Status Tag */}
          {video.status == 2 ? (
            <View style={styles.completedTag}>
              <Text style={styles.completedText}>Completed</Text>
            </View>
          ) : video.status == 3 ? (
            <View style={styles.failureTag}>
              <Text style={styles.failureText}>Failure</Text>
            </View>
          ) : (
            <View>
              <Text style={styles.failureText}>Generating</Text>
            </View>
          )}
        </View>
      </View>
    </View>
  );
};

const History = () => {
  const insets = useSafeAreaInsets();
  const [activeTab, setActiveTab] = useState<number>(0);
  const pagerRef = useRef<PagerView>(null);

  // States for loading
  const [refreshingRole, setRefreshingRole] = useState<boolean>(false);
  const [refreshingTemplate, setRefreshingTemplate] = useState<boolean>(false);
  const [loadingMoreRole, setLoadingMoreRole] = useState<boolean>(false);
  const [loadingMoreTemplate, setLoadingMoreTemplate] = useState<boolean>(false);

  // Videos data
  const [roleVideos, setRoleVideos] = useState<Face.History[]>([]);
  const [templateVideos, setTemplateVideos] = useState<Face.History[]>([]);

  // NextId for pagination
  const [roleNextId, setRoleNextId] = useState<string | undefined>(undefined);
  const [templateNextId, setTemplateNextId] = useState<string | undefined>(undefined);

  // Fetch role videos
  const fetchRoleVideos = useCallback((nextId?: string) => {
    return BusinessAPI.videoList({
      templateType: 1,
      ...(nextId ? { nextId } : {}),
    })
      .then((res) => {
        if (res.code === 0 && res.data.records) {
          return res.data;
        } else {
          showToast.toastOperationFailure();
          return null;
        }
      })
      .catch(() => {
        showToast.toastOperationFailure();
        return null;
      });
  }, []);

  // Fetch template videos
  const fetchTemplateVideos = useCallback((nextId?: string) => {
    return BusinessAPI.videoList({
      templateType: 2,
      ...(nextId ? { nextId } : {}),
    })
      .then((res) => {
        if (res.code === 0 && res.data.records) {
          return res.data;
        } else {
          showToast.toastOperationFailure();
          return null;
        }
      })
      .catch(() => {
        showToast.toastOperationFailure();
        return null;
      });
  }, []);

  // Initial load of role videos
  useEffect(() => {
    fetchRoleVideos().then((data) => {
      if (data) {
        setRoleVideos(data.records);
        setRoleNextId(data.nextId);
      }
    });
  }, [fetchRoleVideos]);

  // Initial load of template videos
  useEffect(() => {
    fetchTemplateVideos().then((data) => {
      if (data) {
        setTemplateVideos(data.records);
        setTemplateNextId(data.nextId);
      }
    });
  }, [fetchTemplateVideos]);

  // Handle refresh for role videos
  const onRefreshRoleVideos = useCallback(() => {
    setRefreshingRole(true);
    fetchRoleVideos().then((data) => {
      if (data) {
        setRoleVideos(data.records);
        setRoleNextId(data.nextId);
      }
      setRefreshingRole(false);
    });
  }, [fetchRoleVideos]);

  // Handle refresh for template videos
  const onRefreshTemplateVideos = useCallback(() => {
    setRefreshingTemplate(true);
    fetchTemplateVideos().then((data) => {
      if (data) {
        setTemplateVideos(data.records);
        setTemplateNextId(data.nextId);
      }
      setRefreshingTemplate(false);
    });
  }, [fetchTemplateVideos]);

  // Handle load more for role videos
  const onLoadMoreRoleVideos = useCallback(() => {
    if (!roleNextId || loadingMoreRole) return;

    setLoadingMoreRole(true);
    fetchRoleVideos(roleNextId).then((data) => {
      if (data) {
        setRoleVideos((prevVideos) => [...prevVideos, ...data.records]);
        setRoleNextId(data.nextId);
      }
      setLoadingMoreRole(false);
    });
  }, [roleNextId, loadingMoreRole, fetchRoleVideos]);

  // Handle load more for template videos
  const onLoadMoreTemplateVideos = useCallback(() => {
    if (!templateNextId || loadingMoreTemplate) return;

    setLoadingMoreTemplate(true);
    fetchTemplateVideos(templateNextId).then((data) => {
      if (data) {
        setTemplateVideos((prevVideos) => [...prevVideos, ...data.records]);
        setTemplateNextId(data.nextId);
      }
      setLoadingMoreTemplate(false);
    });
  }, [templateNextId, loadingMoreTemplate, fetchTemplateVideos]);

  const onTabPress = (index: number) => {
    setActiveTab(index);
    pagerRef.current?.setPage(index);
  };

  const onPageSelected = (e: { nativeEvent: { position: number } }) => {
    setActiveTab(e.nativeEvent.position);
  };

  const renderVideoItem = ({ item }: { item: Face.History }) => <VideoCard video={item} />;

  // Footer component for loading indicator
  const renderFooter = (isLoading: boolean, hasMore: boolean) => {
    if (!isLoading || !hasMore) return null;

    return (
      <View style={styles.footerLoader}>
        <ActivityIndicator size="small" color="#278EFF" />
        <Text style={styles.footerText}>Loading more...</Text>
      </View>
    );
  };

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <StatusBar backgroundColor={'#ffffff'} barStyle="dark-content" />

      {/* Header */}
      <View style={styles.header}>
        <Text style={styles.headerTitle}>My Videos</Text>
      </View>

      {/* Tabs */}
      <View style={styles.tabsContainer}>
        <TouchableOpacity style={[styles.tab, activeTab === 0 && styles.activeTab]} onPress={() => onTabPress(0)}>
          <Text style={[styles.tabText, activeTab === 0 && styles.activeTabText]}>Role Video</Text>
        </TouchableOpacity>
        <TouchableOpacity style={[styles.tab, activeTab === 1 && styles.activeTab]} onPress={() => onTabPress(1)}>
          <Text style={[styles.tabText, activeTab === 1 && styles.activeTabText]}>Templates Video</Text>
        </TouchableOpacity>
      </View>

      {/* Pager View */}
      <PagerView ref={pagerRef} style={styles.pagerView} initialPage={0} onPageSelected={onPageSelected}>
        {/* Role Videos Page */}
        <View key="1" style={styles.pageContainer}>
          <FlashList
            data={roleVideos}
            renderItem={renderVideoItem}
            estimatedItemSize={230}
            contentContainerStyle={styles.listContentContainer}
            showsVerticalScrollIndicator={false}
            onRefresh={onRefreshRoleVideos}
            refreshing={refreshingRole}
            onEndReached={onLoadMoreRoleVideos}
            onEndReachedThreshold={0.5}
            ListFooterComponent={renderFooter(loadingMoreRole, !!roleNextId)}
          />
        </View>

        {/* Template Videos Page */}
        <View key="2" style={styles.pageContainer}>
          <FlashList
            data={templateVideos}
            renderItem={renderVideoItem}
            estimatedItemSize={230}
            contentContainerStyle={styles.listContentContainer}
            showsVerticalScrollIndicator={false}
            onRefresh={onRefreshTemplateVideos}
            refreshing={refreshingTemplate}
            onEndReached={onLoadMoreTemplateVideos}
            onEndReachedThreshold={0.5}
            ListFooterComponent={renderFooter(loadingMoreTemplate, !!templateNextId)}
          />
        </View>
      </PagerView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
  },
  header: {
    paddingHorizontal: pxToVw(20),
    paddingVertical: pxToVh(15),
  },
  headerTitle: {
    fontSize: pxToVh(24),
    fontWeight: '600',
    color: '#000000',
  },
  tabsContainer: {
    flexDirection: 'row',
    paddingHorizontal: pxToVw(20),
    borderBottomWidth: 1,
    borderBottomColor: '#E0E0E0',
  },
  tab: {
    paddingVertical: pxToVh(10),
    marginRight: pxToVw(20),
  },
  activeTab: {
    borderBottomWidth: 2,
    borderBottomColor: '#278EFF',
  },
  tabText: {
    fontSize: pxToVh(16),
    color: '#9D9D9D',
  },
  activeTabText: {
    color: '#278EFF',
    fontWeight: '500',
  },
  pagerView: {
    flex: 1,
  },
  pageContainer: {
    flex: 1,
    paddingHorizontal: pxToVw(20),
  },
  listContentContainer: {
    paddingVertical: pxToVh(15),
  },
  videoCard: {
    backgroundColor: '#FFFFFF',
    borderRadius: 8,
    marginBottom: pxToVh(15),
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3,
    elevation: 3,
  },
  videoPreview: {
    height: pxToVh(180),
    backgroundColor: '#F5F5F5',
    borderTopLeftRadius: 8,
    borderTopRightRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  playButton: {
    width: pxToVw(40),
    height: pxToVw(40),
    backgroundColor: 'rgba(255, 255, 255, 0.8)',
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
  videoInfo: {
    padding: pxToVw(15),
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  videoInfoContent: {
    flex: 1,
    justifyContent: 'center',
  },
  rightContainer: {
    alignItems: 'flex-end',
    justifyContent: 'center',
    marginLeft: pxToVw(10),
  },
  videoTitle: {
    fontSize: pxToVh(16),
    fontWeight: '500',
    color: '#000000',
  },
  videoDuration: {
    fontSize: pxToVh(14),
    color: '#757575',
    marginTop: pxToVh(4),
  },
  videoCreated: {
    fontSize: pxToVh(12),
    color: '#9E9E9E',
    marginTop: pxToVh(4),
  },
  actionButtonsContainer: {
    flexDirection: 'row',
    marginBottom: pxToVh(8),
  },
  actionButton: {
    width: pxToVw(32),
    height: pxToVw(32),
    marginLeft: pxToVw(8),
  },
  actionButtonInner: {
    width: '100%',
    height: '100%',
    borderRadius: pxToVw(16),
    backgroundColor: '#F0F0F0',
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#E5E5E5',
  },
  completedTag: {
    paddingHorizontal: pxToVw(8),
    paddingVertical: pxToVh(4),
    backgroundColor: '#E8F5E9',
    borderRadius: 4,
    alignSelf: 'flex-end',
  },
  completedText: {
    fontSize: pxToVh(12),
    color: '#4CAF50',
    fontWeight: '500',
  },
  failureTag: {
    paddingHorizontal: pxToVw(8),
    paddingVertical: pxToVh(4),
    backgroundColor: '#FFEBEE',
    borderRadius: 4,
    alignSelf: 'flex-end',
  },
  failureText: {
    fontSize: pxToVh(12),
    color: '#F44336',
    fontWeight: '500',
  },
  video: {
    width: '100%',
    height: '100%',
  },
  footerLoader: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: pxToVh(15),
  },
  footerText: {
    marginLeft: pxToVw(8),
    fontSize: pxToVh(14),
    color: '#757575',
  },
});

export default History;
